package jvm.gc;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/*
*
* 强 软 弱 虚    引用
* */
public class Test4 {
    public static void main(String[] args) {
//        test1();
          test2();
    }
    /*测试软引用*/
    public static void test1() {//当内存资源非常紧张是就会回收软引用对象
        byte[] bytes = new byte[1024 * 1024 * 6];
        User zs = new User("zs", 18);
        SoftReference<User> softReference = new SoftReference<>(zs);
        zs = null;
        System.out.println(softReference.get() + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        try {
            byte[] bytes1 = new byte[1024 * 1024];
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
//            System.out.println(softReference.get()+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");//这里会掉用user的toString方法
            User user = softReference.get();
            System.out.println(user);
        }
    }
    /*测试虚引用*/
    public static void test2(){//在任何一次gc时 发现即回收
        WeakReference<User> ls = new WeakReference<>(new User("ls", 19));
        System.out.println(ls.get());
        System.gc();
        System.out.println(ls.get());
    }
}
class User{
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
